package com.atguigu.eduservice.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/12/7
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    //不能交给Spring进行管理，需要new，不能注入
    public EduSubjectService subjectService;

    public SubjectExcelListener() {}

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //一行一行读数据
    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if (data == null) {
            throw new GuliException(20001, "文件数据为空");
        }
        //一行一行读取，每次读取有两个值，一级分类和二级分类
        //判断一级分类是否重复
        EduSubject OneEduSubject = this.existOneSubject(subjectService, data.getOneSubjectName());
        if (OneEduSubject == null) {
            //没有相同字段进行添加
            OneEduSubject = new EduSubject();
            OneEduSubject.setParentId("0");
            OneEduSubject.setTitle(data.getOneSubjectName());
            subjectService.save(OneEduSubject);
        }
        //判断二级分类是否重复
        String pid = OneEduSubject.getId();
        EduSubject TwoEduSubject = this.existTwoSubject(subjectService, data.getTwoSubjectName(), pid);
        if (TwoEduSubject == null) {
            //没有相同字段进行添加
            TwoEduSubject = new EduSubject();
            TwoEduSubject.setParentId(pid);
            TwoEduSubject.setTitle(data.getTwoSubjectName());
            subjectService.save(TwoEduSubject);
        }
    }

    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService subjectService, String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(EduSubject::getTitle, name).eq(EduSubject::getParentId, "0");
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }
    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService subjectService, String name,String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(EduSubject::getTitle, name).eq(EduSubject::getParentId, "0").eq(EduSubject::getParentId,pid);
        EduSubject twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
